package com.fgxia.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fgxia.user.service.ISiteInfoService;
import com.ruoyi.business.domain.SiteInfo;
import com.ruoyi.business.domain.bo.SiteInfoBo;
import com.ruoyi.business.domain.vo.SiteInfoVo;
import com.ruoyi.business.mapper.SiteInfoMapper;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.SysYesNo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 地址信息 Service
 *
 * @author yyt
 * @date 2024-04-20
 */
@Service
@RequiredArgsConstructor
public class SiteInfoServiceImpl implements ISiteInfoService {

    private final SiteInfoMapper baseMapper;

    @Override
    public Boolean insertByBo(SiteInfoBo bo) {
        SiteInfo siteInfo = BeanUtil.toBean(bo, SiteInfo.class);
        return baseMapper.insert(siteInfo) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(SiteInfoBo bo) {
        SiteInfo siteInfo = BeanUtil.toBean(bo, SiteInfo.class);
        if (SysYesNo.Y.name().equals(siteInfo.getIsDefault())) {
            // If so, set all other records to non-default
            LambdaUpdateWrapper<SiteInfo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(SiteInfo::getIsDefault, SysYesNo.N)
                .eq(SiteInfo::getRelevanceUserId, siteInfo.getRelevanceUserId());
            baseMapper.update(null, updateWrapper);
        }
        return baseMapper.updateById(siteInfo) > 0;
    }

    @Override
    public TableDataInfo<SiteInfoVo> selectVoList(SiteInfo siteInfo, PageQuery pageQuery) {
        LambdaQueryWrapper<SiteInfo> lqw = new LambdaQueryWrapper<SiteInfo>()
            .eq(SiteInfo::getRelevanceUserId, siteInfo.getRelevanceUserId())
            .orderByDesc(SiteInfo::getIsDefault, SiteInfo::getUpdateTime);
        IPage<SiteInfoVo> page = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }

    @Override
    public Boolean deleteById(Long siteId) {
        return baseMapper.deleteById(siteId) > 0;
    }

}
